package top.guxx.springframework.beans.factory.support;

import top.guxx.springframework.beans.BeansException;
import top.guxx.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author：Guxx
 * @Description：JDK创建Bean实例
 * @Date：2024/6/9 15:05
 * @Filename：SimpleInstantiationStrategy
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) throws BeansException {
        //1.拿到要创建Bean的类信息
        Class clazz = beanDefinition.getBeanClass();
        try {
            //2.判断是否有参
            if (constructor != null){
                //2.1 创建有参实例
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            }else {
                //2.2 创建无参实例
                return clazz.getDeclaredConstructor().newInstance();
            }
        }catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e){
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "] ", e);
        }

    }
}
